<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import va from '@/rules/index'
import type { FormInstance, FormRules } from 'element-plus'

// Types
type ExportRange = 1 | 2 | 3
type FileType = 'excel' | 'json' | 'xml'
type NameType = 0 | 1

interface FieldItem {
  prop: string
  label: string
  [key: string]: unknown
}

interface FormData {
  fields: string[]
  range: ExportRange
  fileType: FileType
  nameType: NameType
  fileName: string
}

interface FormDialog {
  top: string
  width: string
  title: string
  visible: boolean
}

// Props

interface ComponentProps {
  fields?: FieldItem[]
}

// Props with defaults
const props = withDefaults(defineProps<ComponentProps>(), {
  fields: () => [],
})

// Emits
const emit = defineEmits<{
  (e: 'success'): void
}>()

// Refs
const formRef = ref<FormInstance>()
const checkAll = ref(false)
const isIndeterminate = ref(false)
const saveLoading = ref(false)

// Data
const formData = ref<FormData>({
  fields: [],
  range: 1,
  fileType: 'excel',
  nameType: 0,
  fileName: '',
})

const formDialog = reactive<FormDialog>({
  top: '10vh',
  width: '960px',
  title: '导出',
  visible: false,
})

const fieldsList = computed(() =>
  (props.fields || []).map((i) => ({
    key: i.prop,
    ...i,
  })),
)

// Validation rules
const formRules = reactive<FormRules<FormData>>({
  range: [va.required()],
  fields: [va.required('请选择需要导出的字段')],
  fileType: [va.required()],
  nameType: [va.required()],
  fileName: [va.required()],
})

// Methods
const show = (): void => {
  formDialog.visible = true
}

const saveForm = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) return

  saveLoading.value = true
  try {
    const valid = await formEl.validate()
    if (valid) {
      console.log('表单内容', formData.value)
      // Add your export logic here
      emit('success')
    }
  } catch (errors) {
    console.log('Validation errors:', errors)
  } finally {
    saveLoading.value = false
  }
}

const handleCheckAllChange = (val: boolean): void => {
  formData.value.fields = val ? fieldsList.value.map((i) => i.key) : []
  isIndeterminate.value = false
}

const handleCheckedCitiesChange = (value: string[]): void => {
  const checkedCount = value.length
  checkAll.value = checkedCount === fieldsList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < fieldsList.value.length
}

defineExpose({ show })
</script>

<template>
  <el-tooltip effect="dark" content="导出数据" placement="top">
    <el-button type="primary" icon="Download" plain @click="show" />
  </el-tooltip>

  <el-dialog
    :title="formDialog.title"
    v-model="formDialog.visible"
    :top="formDialog.top"
    :width="formDialog.width"
    :close-on-click-modal="false"
    :append-to-body="true"
    destroy-on-close
  >
    <el-form
      :model="formData"
      :rules="formRules"
      ref="formRef"
      label-width="90px"
      label-suffix=":"
      label-position="top"
    >
      <el-form-item label="数据范围" prop="range">
        <el-radio-group v-model="formData.range">
          <el-radio :value="1">当前页数据</el-radio>
          <el-radio :value="2">当前过滤数据</el-radio>
          <el-radio :value="3">所有数据</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="字段选择" prop="fields">
        <div class="w-full">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
            <span class="text-gray-600">
              (<span class="text-red-600">{{ formData.fields.length }}</span
              >/ <span>{{ fieldsList.length }}</span
              >)
            </span>
          </el-checkbox>
          <el-checkbox-group v-model="formData.fields" @change="handleCheckedCitiesChange">
            <el-row :gutter="20">
              <el-col :span="8" v-for="i in fieldsList" :key="i.key">
                <el-checkbox :label="i.label" :value="i.key" />
              </el-col>
            </el-row>
          </el-checkbox-group>
        </div>
      </el-form-item>

      <el-form-item label="导出格式" prop="fileType">
        <el-radio-group v-model="formData.fileType">
          <el-radio value="excel">Excel</el-radio>
          <el-radio value="json">Json</el-radio>
          <el-radio value="xml">Xml</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="文件名" prop="nameType">
        <el-radio-group v-model="formData.nameType">
          <el-radio :value="0">系统生成</el-radio>
          <el-radio :value="1">自定义</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="" prop="fileName">
        <el-input v-model="formData.fileName" maxlength="100" placeholder="文件名" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button
          type="primary"
          @click="saveForm(formRef)"
          icon="Download"
          :loading="saveLoading"
          auto-insert-space
        >
          导出
        </el-button>
        <el-button @click="formDialog.visible = false" icon="CircleClose" auto-insert-space>
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
